package com.sunmi.sbs.commons.utils;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.*;

/**
 * author: fanjia
 * date: 2020/9/19 11:08
 * file: JDBCUtils.java
 */
public class JDBCUtils {
    public static Connection connectDatabase(HashMap jdbcProp) {
        String driver = "com.mysql.jdbc.Driver";
        try {
            Connection conn;
            Class.forName(driver);
            conn = (Connection) DriverManager.getConnection(jdbcProp.get("url").toString(), jdbcProp.get("username").toString(), jdbcProp.get("password").toString());
            if (conn != null) {
                return conn;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static HashMap prepareQuery(Connection connection, String sql, String[] queryParams, String[] resultParams) {
        List query = Arrays.asList(queryParams);
        List lists = Arrays.asList(resultParams);
        Connection conn;
        PreparedStatement stmt;
        HashMap hashmap = new HashMap();
        try {
            if (connection != null) {
                conn = connection;
                stmt = (PreparedStatement) conn.prepareStatement(sql);
                for (int i = 0; i < query.size(); i++) {
                    stmt.setString(i + 1, (String) query.get(i));
                    System.out.println(query.get(i));
                }
                ResultSet rs = stmt.executeQuery();
                rs.last();
                System.out.println(rs.getRow());
                rs.beforeFirst();
                if (rs.next()) {
                    for (Object list : lists) {
                        hashmap.put(list, String.valueOf(rs.getString((String) list)));
                    }
                } else {
                    System.out.println("error");
                }
                rs.close();
                stmt.close();
                conn.close();

            }
            return hashmap;

        } catch (SQLException se) {
            se.printStackTrace();
        }
        return hashmap;

    }


}
